// -------------------------------------------------------------------------------------------------------------------
//
//  File: RTLSDisplayApplication.cpp
//
//  Copyright 2016 (c) Decawave Ltd, Dublin, Ireland.
//
//  All rights reserved.
//
//  Author:
//
// -------------------------------------------------------------------------------------------------------------------

#include "RTLSDisplayApplication.h"

#include "mainwindow.h"

#include "moveaction.h"

#include <QMetaProperty>
#include <QDesktopWidget>
#include "tools/leiliconfig.h"


RTLSDisplayApplication::RTLSDisplayApplication(int &argc, char **argv) : QApplication(argc, argv)
{
    this->onChangeStyle(":/qss/Ubuntu.qss");


    QDesktopWidget desktop;
    int desktopHeight=desktop.geometry().height();
    int desktopWidth=desktop.geometry().width();

    _ready = false;

    this->setOrganizationName("leili");
    this->setOrganizationDomain("http://www.leilitools.cn/");
    this->setApplicationName("leili");


    _moveAction = new MoveAction(this);

    _mainWindow = new MainWindow();
    _mainWindow->resize(desktopWidth/2,desktopHeight/2);

    _ready = true;


    QObject::connect(this, SIGNAL(statusBarMessage(QtMsgType,QString)), _mainWindow, SLOT(statusBarMessage(QtMsgType,QString)));

    //emit ready signal so other components can finish initialisation
    emit ready();
}

RTLSDisplayApplication::~RTLSDisplayApplication()
{
    // Delete the objects manually, because we want to control the order
    delete _mainWindow;


    LeiliCfg->save();
}

RTLSDisplayApplication *RTLSDisplayApplication::instance()
{
    return qobject_cast<RTLSDisplayApplication *>(QCoreApplication::instance());
}



MainWindow *RTLSDisplayApplication::mainWindow()
{
    return instance()->_mainWindow;
}





MoveAction *RTLSDisplayApplication::moveAction()
{
    return instance()->_moveAction;
}

SLAMwidget *RTLSDisplayApplication::pathWidget()
{
    return mainWindow()->pathWidget();
}

void RTLSDisplayApplication::connectReady(QObject *receiver, const char *member, Qt::ConnectionType type)
{
    QMetaMethod method = receiver->metaObject()->method(receiver->metaObject()->indexOfMethod(QMetaObject::normalizedSignature(member)));
    // Either call the method or connect it to the ready signal

    if (instance()->_ready && method.isValid())
        method.invoke(receiver, type);
    else
        QObject::connect(instance(), QMetaMethod::fromSignal(&RTLSDisplayApplication::ready), receiver, method, type);
}

void RTLSDisplayApplication::onChangeStyle(const QString &qss)
{
    QFile file(qss);
    if( file.open(QFile::ReadOnly))
    {
       QString styleSheet = QLatin1String(file.readAll());

       setStyleSheet(styleSheet);
       file.close();
    }
}

